//获取应用实例
var app = getApp();
//获得

var MyRequest = require("../../utils/MyRequest.js");
var Global = require("../../Global.js");
var util = require('../../utils/util.js');
var Cart = require("../../LocalCart.js");


Page({
  //页面初始化的数据
  data: {
    Switch: true,
    Page: 0,
    Count: 10,
    detailImage: "",
    CloseTime: "",
    ClassId: "",
    isShowBigImg: "hide"
  },
  //请求数据者者  
  //请求数据者
  Presenter: {
    getHome: function (that) {
      var data = { "action": "productType", "begin": 0, "end": that.data.Count, "classId": that.data.ClassId };
      MyRequest.MyGetWithToast("ProductList", that, that.Binder.bindHome, data);
    },
    Refresh: function (that) {
      var data = { "action": "productType", "begin": 0, "end": that.data.Count, "classId": that.data.ClassId };
      MyRequest.MyGetWithRefresh("ProductList", that, that.Binder.bindHome, data);
    },
    Pull: function (that) {
      that.setData({
        Page: that.data.Page + 1
      })
      var data = { "action": "productType", "begin": that.data.Page * that.data.Count, "end": (that.data.Page + 1) * that.data.Count, "classId": that.data.ClassId };
      MyRequest.MyGetWithToast("ProductList", that, that.Binder.bindPull, data);
    },
    //获取时间数据
    getActiveDay: function (that) {
      var data = { "action": "weekday" };
      MyRequest.MyGet("ActiveDay", that, that.Binder.bindActiveDay, data);
    }
  },
  //数据绑定
  Binder: {
    bindHome: function (result, that) {
      var curDate = that.data.activeDay[that.data.currentTime]
      that.setData({
        products: Cart.solveProductData(result.data.data, curDate.detaildate)
      });
    },
    bindPull: function (result, that) {
      var total = result.data.total;
      if (total > 0) {
        var data = result.data.data;
        var newData = that.data.products;
        for (var i = 0; i < data.length; i++) {
          newData.push(data[i]);
        }
        var curDate = that.data.activeDay[that.data.currentTime]
        that.setData({
          products: Cart.solveProductData(newData, curDate.detaildate)
        });
      }
    },
    bindActiveDay: function (result, that) {


      let dataset = result.data.data;
      var currentTime;
      var TimeState = new Array();
      for (var i = 0; i < dataset.length; i++) {
        var date = dataset[i].wdate.substr(5);
        var week = dataset[i].wday;
        if (dataset[i].state == 2) {
          currentTime = i;
          TimeState[i] = "selected";
        } else if (dataset[i].state == 1) {
          TimeState[i] = "not-optional";
        } else {
          TimeState[i] = "optional";
        }

        var w = Cart.solveDate(week);
        dataset[i].detaildate = dataset[i].wdate;
        dataset[i].wdate = date;
        dataset[i].weekday = w;
      }

      that.setData({
        activeDay: dataset,
        currentTime: currentTime,
        TimeState: TimeState
      })
      that.Presenter.getHome(that);
    }
  },
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: options.className
    });
    var dd = util.formatTime(new Date);
    var date1 = new Date(dd);  //开始时间
    dd = dd.substr(0, 11);
    var date2 = new Date(dd + options.closetime);    //结束时间
    //var date2 = new Date("2017-02-06 16:08");
    var date3 = date2.getTime() - date1.getTime();
    //计算出小时数

    var leave1 = date3 % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000))
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000)        //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000))
    var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000)

    this.setData({
      detailImage: options.detailImage,
      CloseTime: hours + ":" + minutes + ":" + seconds,
      ClassId: options.classId,
      CartCount: Cart.countCartNum(),
      CartPrice: Cart.countCartPrice(),
      Carts: Cart.geCartStorage(),
      isShowCart: "hide"
    });

    if (date3 < 0) {
      this.setData({
        CloseTime: "已打烊"
      });

    }
    this.Presenter.getActiveDay(this);

    this.CountDown(this);
  },
  //用户下拉
  onPullDownRefresh: function () {
    // 阻止下拉
    this.setData({
      Page: 0
    })
    this.Presenter.Refresh(this);

  },
  //下拉触底
  onReachBottom: function () {
    this.Presenter.Pull(this);
  },
  onSwitchTime: function (event) {
    var index = event.currentTarget.dataset.index;
    var lastIndex = this.data.currentTime;
    if (index == lastIndex) {
      return;
    }
    var times = this.data.TimeState;
    times[index] = "selected";
    times[lastIndex] = "optional";
    this.setData({
      TimeState: times,
      currentTime: index,
      products: Cart.solveProductData(this.data.products, this.data.activeDay[index].detaildate)
    });
  },
  CountDown: function countdown(that) {
    var time = that.data.CloseTime;
    if (time == "已打烊") {
      return;
    }

    var t = setInterval(function () {
      var time = that.data.CloseTime;
      var t = time.split(":");
      var hour = t[0];
      var minute = t[1];
      var second = t[2];
      if (hour < 0) {
        that.setData({
          CloseTime: "已打烊"
        });
        clearInterval(t);
        return;
      }
      second--;
      if (second < 0) {
        second = 59;
        minute--;
        if (minute < 0) {
          minute = 59;
          hour--;
          if (hour < 0) {
            that.setData({
              CloseTime: "已打烊"
            });
            clearInterval(t);
            return;
          }
        }
      }
      hour = (Array(2).join('0') + hour).slice(-2);
      minute = (Array(2).join('0') + minute).slice(-2);
      second = (Array(2).join('0') + second).slice(-2);
      that.setData({

        CloseTime: hour + ":" + minute + ":" + second
      });
      that.setData({
        second: second - 1
      });
    }, 1000);

  },
  addCart: function (event) {
    var product = event.target.dataset.product;
    var curDate = this.data.activeDay[this.data.currentTime];
    Cart.setCartStorage(product, curDate.detaildate, curDate.wday);
    this.setData({
      CartCount: Cart.countCartNum(),
      CartPrice: Cart.countCartPrice(),
      products: Cart.solveProductData(this.data.products, curDate.detaildate)
    });
  },
  subCart: function (event) {
    var product = event.target.dataset.product;
    var curDate = this.data.activeDay[this.data.currentTime]
    Cart.subCartNum(product, curDate.detaildate);
    this.setData({
      CartCount: Cart.countCartNum(),
      CartPrice: Cart.countCartPrice(),
      products: Cart.solveProductData(this.data.products, curDate.detaildate)
    });
  },
  onReady: function () {
    if (this.data.CloseTime == "已打烊") {
      wx.showToast({
        title: '已打烊',
        duration: 6000,
      });
    }
  },
  toCart: function () {
    if (!Global.getUserStorage()) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
    } else {
      wx.redirectTo({
       url: '/pages/cart/cart',        
      })
    }

  },
  showCart: function () {
    if (this.data.isShowCart == "show") {
      return;
    }
    this.setData({
      isShowCart: "show",
      Carts: Cart.geCartStorage()
    });
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease',
    });

    animation.bottom(0).step();

    this.setData({
      animationData: animation.export()
    })
  },
  hideCart: function () {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease',
    });

    animation.bottom("-100%").step();

    this.setData({
      animationData: animation.export()
    });
    var that = this;
    setTimeout(function () {
      that.setData({
        isShowCart: "hide"
      });
    }, 200);
  },
  delCart: function (event) {
    var index = event.currentTarget.dataset.index;
    Cart.updateCartNum(this.data.Carts[index], 2);
    var date = this.data.Carts[index].date;
    this.setData({
      CartCount: Cart.countCartNum(),
      CartPrice: Cart.countCartPrice(),
      Carts: Cart.geCartStorage(),
      products: Cart.solveProductData(this.data.products, date)
    });
  },
  addCartDetail: function (event) {
    var index = event.currentTarget.dataset.index;
    Cart.updateCartNum(this.data.Carts[index], 1);
    var date = this.data.Carts[index].date;
    this.setData({
      CartCount: Cart.countCartNum(),
      CartPrice: Cart.countCartPrice(),
      Carts: Cart.geCartStorage(),
      products: Cart.solveProductData(this.data.products, date)
    });
  },
  clearCart: function () {
    Cart.clearCartStorage();
    this.setData({
      CartCount: Cart.countCartNum(),
      CartPrice: Cart.countCartPrice(),
      Carts: Cart.geCartStorage(),
      products: Cart.solveProductData(this.data.products)
    });
    this.hideCart();
  },
  showBigImage: function (event) {
    var url = event.currentTarget.dataset.imgurl;
    this.setData({
      isShowBigImg: "show",
      bigImage: url
    });
  },
  hideBigImg: function () {
    this.setData({
      isShowBigImg: "hide"
    });
  },
  onShow: function () {
    this.setData({
      CartCount: Cart.countCartNum(),
      CartPrice: Cart.countCartPrice(),
      Carts: Cart.geCartStorage(),
    });
  }
})